package com.yc.demo.web;

import com.google.gson.Gson;
import com.yc.demo.mapper.TestMapper;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

@ServerEndpoint("/talk/{id}")
@Component
public class TalkServer {

    Hashtable<String,Session> sessions;

    //Spring
  static TestMapper testMapper;
    public void  setTestMapper(TestMapper testMapper){
        TalkServer.testMapper = testMapper;
    };
    @OnOpen
    public void onOpen(@PathParam("id") String id, Session session){

        sessions.values().forEach(s->{
            send(session,new Msg(
                    ""+session.getUserProperties().get("id"),
                    null,id,"shangxianle"));
        });
        List<Map<String, Object>> list = testMapper.selectAllAcount();
        sessions.put(id,session);
        session.getUserProperties().put("id",id);
        sessions.values().forEach(s->{
            send(s,new Msg(
                    id,null, id,"shangxianle"));
        });
    }
    @OnClose
    public void onClose( Session session){
        String id =(String) session.getUserProperties().get("id");
        sessions.remove(id);
        sessions.values().forEach(s->{
            send(session,new Msg(null,id,id,"xiaxianle"));
        });
    }
    //
    @OnMessage
    public void onMessage(String message,Session session){
        //
        sessions.values().forEach(s -> {
            send(session,new Msg(null,null,(String)session.getUserProperties().get("id"),message));
        });


    }
    Gson gson =new Gson();
    //给指定的客户端发送消息
    public void send(Session session,Object o){
        String json = gson.toJson(o);
        try {
            session.getBasicRemote().sendText(json);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
@Data
@NoArgsConstructor
@AllArgsConstructor
class Msg{
    String onlineUser; //
    String downlineUser;
    String sendUser;
    String sendMsg;
}